﻿using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using FastExpressionCompiler.LightExpression;
using HandyControl.Controls;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Client.Views;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Trade;
using Prism.Commands;
using Prism.DryIoc;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using VolumeIndex = PlaceOrder_Shared.Models.Trade.VolumeIndex;
using System.Timers;
namespace PlaceOrder_Client.ViewModels
{  

    /// <summary>
    /// 龙虎榜单
    /// </summary>
    public class LongHuViewModel:Prism.Mvvm.BindableBase
    {



        #region 依赖属性
        /// <summary>
        /// 标记是否置顶
        /// </summary>
        private bool isTopMost = false;

        public bool IsTopMost
        {
            get { return isTopMost; }
            set { isTopMost = value; RaisePropertyChanged(); }
        }

        #endregion


        #region 命令
        public Prism.Commands.DelegateCommand<VolumeIndex> SelectedTradeCommand { get; private set; }
        public Prism.Commands.DelegateCommand SetTopMostCommand { get; private set; } //置顶页面
        #endregion
        private readonly IDailyData _dailyData;
        private ClientWebSocketHelper clientWebsocket = new ClientWebSocketHelper();
        private TradeSimUser TradeUser = new TradeSimUser();

        private List<VolumeIndex> TotalVolumeList = new List<VolumeIndex>(); // 所有成交信息（为之后筛选用）
        private string strVer = string.Empty;

        public Prism.Commands.DelegateCommand AddCommand { get; set; }


        private System.Timers.Timer _reconnectTimer;
        /// <summary>
        /// 龙虎榜（30条）
        /// </summary>
        private ObservableCollection<VolumeIndex> volumeList;

        public ObservableCollection<VolumeIndex> VolumeList
        {
            get { return volumeList; }
            set { volumeList = value; RaisePropertyChanged(); }
        }

        public LongHuViewModel(IDailyData dailyData)
        {
            //VolumeList = new ObservableCollection<VolumeIndex>();
            //VolumeList.Add(new VolumeIndex() { ChangeBP=11,HighPrice=22 });

            _dailyData = dailyData;

            InitCommand();
            InitValue();
            StartService();

            // 注册接收器
            Messenger.Default.Register<string>(this, "longhuClosed", HandleLonghuClosed);
            //StartServiceAsync();

            // 初始化并启动定时器
            InitializeSubscriptionTimer();
        }
        private void InitializeSubscriptionTimer()
        {
            _subscriptionTimer = new System.Timers.Timer(10*60* 1000); // 15分钟重新订阅一次龙虎榜
            _subscriptionTimer.Elapsed += OnSubscriptionTimerElapsed;
            _subscriptionTimer.AutoReset = true; // 设置为自动重置
            _subscriptionTimer.Enabled = true; // 启动定时器
        }
        private System.Timers.Timer _subscriptionTimer;
        private void OnSubscriptionTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 确保在UI线程上更新
            HandleLonghuClosed("1");

            AppLog.WriteInfo("定时时间到，重新订阅龙虎榜！");
        }

        private void StopSubscriptionTimer()
        {
            if (_subscriptionTimer != null)
            {
                _subscriptionTimer.Stop();
                _subscriptionTimer.Dispose();
            }
        }
        private async void HandleLonghuClosed(string obj)
        {
            //Thread.Sleep(30000);
            try
            {
                clientWebsocket.SubscribeIndexEvent -= HandleIndexEvent;

                clientWebsocket.SubscribeIndexEvent += HandleIndexEvent;

                // 使用异步延迟，避免阻塞
                await Task.Delay(1000);

                clientWebsocket.SubscribeVolumeIndex();

                AppLog.WriteInfo("重新订阅龙虎榜！");
            }
            catch(Exception ex)
            {
                AppLog.WriteError("重新订阅龙虎榜异常！！！"+ex.Message);

            }

            //if (!_webSocket.IsAlive)
            //{
            //    _reconnectTimer.Start();
            //}
        }

        private void InitCommand()
        {
            SelectedTradeCommand = new Prism.Commands.DelegateCommand<VolumeIndex>(SelectedTradeHandle);
            SetTopMostCommand = new Prism.Commands.DelegateCommand(SetTopMostWindow);
        }

        private void SetTopMostWindow()
        {
            // 获取当前窗口并置顶
            var currentWindow = PrismApplication.Current.Windows.OfType<System.Windows.Window>().SingleOrDefault(w => w.IsActive);
            if (currentWindow != null)
            {
                IsTopMost = !IsTopMost;
                currentWindow.Topmost = IsTopMost;
            }
        }

        private bool isHandlingOpen = false; // 增加一个标志位来控制是否正在处理打开窗口操作
        /// <summary>
        /// 双击打开一个orderview
        /// </summary>
        /// <param name="index"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void SelectedTradeHandle(VolumeIndex volume)
        {
            try
            {
                decimal price1 = volume.Price;
                int volume1 = volume.Volume;


                if (isHandlingOpen)
                {
                    Growl.WarningGlobal("有正在打开的窗口，请稍后...");
                    return; // 如果正在处理打开窗口操作，直接返回，避免重复执行
                }

                isHandlingOpen = true; // 设置标志位为 true，表示正在处理打开窗口操作
                if(!OrderListViewModel.CheckIfInWhiteList(volume.TsCode))
                {
                    Growl.WarningGlobal($"{volume.TsCode}不在券码白名单中，请检查！");
                    return;
                }
                OrderView orderView = new OrderView();

                await Task.Run(() =>
                {
                    PrismApplication.Current.Dispatcher.Invoke(() =>
                    {
                        orderView.Show();
                    });
                });

                orderView._vm.BondNumber = volume.TsCode;
                //await Task.Delay(0);
                await orderView._vm.OnTsSelectionChangedAsync(volume.TsCode,true);





                isHandlingOpen = false; // 设置标志位为 true，表示正在处理打开窗口操作
                // 设置视图模型的属性
                //orderViewModel.BondNumber = volume.TsCode; // 替换为您要设置的属性和值
            }
            catch(Exception ex)
            {
                AppLog.WriteError("双击龙虎榜异常"+ex.StackTrace+ex.Message);
            }
            finally
            {
                isHandlingOpen = false;
            }
        }

        private void InitValue()
        {
            TestCommand = new Prism.Commands.DelegateCommand(() =>
            {
                this.clientWebsocket.UnsubscribeVolumeIndex();
            });
        }
        public Prism.Commands.DelegateCommand TestCommand { get; set; }
        private void StartService()
        {
            //Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            //strVer = $"{ver.Major}.{ver.Minor}.{ver.Build:D4}.{ver.Revision:D3}";
            clientWebsocket.SubscribeIndexEvent -= HandleIndexEvent;

            clientWebsocket.SubscribeIndexEvent += HandleIndexEvent;

             clientWebsocket.SubscribeVolumeIndex();
        }
        private async Task StartServiceAsync()
        {
            Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            strVer = $"{ver.Major}.{ver.Minor}.{ver.Build:D4}.{ver.Revision:D3}";
            clientWebsocket.SubscribeIndexEvent -= HandleIndexEvent;

            clientWebsocket.SubscribeIndexEvent += HandleIndexEvent;

            await clientWebsocket.SubscribeVolumeIndexAsync();
        }

        /// <summary>
        /// 处理成交排行榜数据,并行优化 0707
        /// </summary>
        /// <param name="index"></param>
        /// 
        private void HandleIndexEvent(List<VolumeIndex> index)
        {
            if (index.Count > 0)
            {
                //AppLog.WriteWarn($"收到龙虎榜数据{index.Count}条");
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    Parallel.ForEach(index, v =>
                    {
                        VolumeIndex volume;
                        lock (TotalVolumeList)
                        {
                            volume = TotalVolumeList.SingleOrDefault(x => x.TsCode == v.TsCode);

                            if (volume == null)
                            {
                                //var tsInfo = DataHelper.TsInfos.FirstOrDefault(ts => ts.tsCode == v.TsCode);
                                //if (tsInfo != null)
                                //{
                                //    v.Year = tsInfo.Maturity;
                                //    v.PVBP = tsInfo.PVBP.ToString();
                                //}
                                lock (TotalVolumeList)
                                {
                                    TotalVolumeList.Add(v);
                                }
                            }
                            else
                            {
                                lock (volume)
                                {
                                    volume.Volume = v.Volume;
                                    //volume.TradeTime = v.TradeTime;

                                    // 转换为 TimeOnly，保留小时、分钟和秒信息
                                    volume.TradeTime = v.TradeTime;
                                    volume.Price = v.Price;
                                    volume.HighPrice = v.HighPrice;
                                    volume.LowPrice = v.LowPrice;
                                    volume.ChangeBP = v.ChangeBP;
                                }
                            }
                        }


                    });

                    VolumeList = TotalVolumeList
                        .OrderByDescending(x => x.Volume)
                        .Take(30)
                        .ToObservableCollection();
                });
            }
        }

        //private void HandleIndexEvent(List<VolumeIndex> index)
        //{
        //    if (index.Count > 0)
        //    {
        //        PrismApplication.Current.Dispatcher.Invoke(() =>
        //        {
        //            foreach (var v in index)
        //            {
        //                VolumeIndex volume = TotalVolumeList.SingleOrDefault(x => x.TsCode == v.TsCode);

        //                if (volume == null)
        //                {
        //                    var tsInfo = DataHelper.TsInfos.FirstOrDefault(ts => ts.tsCode == v.TsCode);
        //                    if (tsInfo != null)
        //                    {
        //                        v.Year = tsInfo.Maturity;
        //                        v.PVBP = tsInfo.PVBP.ToString();
        //                    }
        //                    TotalVolumeList.Add(v);
        //                }
        //                else
        //                {
        //                    volume.Volume = v.Volume;
        //                    volume.TradeTime = v.TradeTime;
        //                    volume.Price = v.Price;
        //                    volume.ChangeBP = v.ChangeBP;
        //                }
        //            }

        //            VolumeList = TotalVolumeList.OrderByDescending(x => x.Volume).Take(30).ToObservableCollection();
        //        });
        //    }
        //}





        #region websocket相关
        /// <summary>
        /// WebSocket断开重连机制
        /// </summary>
        private void Reconnect()
        {
           
        }
        #endregion
    }
}
